package org.example.redis.impl;

import org.example.redis.Limiter;

/**
 * 漏斗限流器
 * 以固定的速率流出
 */
public class FunnelLimiter implements Limiter {

    /**
     * 每秒放行2次
     */
    private static final int rate = 2;

    /**
     * 剩余多少水量
     */
    private int water;

    /**
     * 漏斗的容量
     */
    private final int capacity = 10;

    /**
     * 当前时间
     */
    private long currTime = System.currentTimeMillis();

    @Override
    public boolean tryAcquire(int count) {
        long nowTs = System.currentTimeMillis();
        // 已经过去了多长时间
        long diff = nowTs - currTime;
        // 流出的水量
        int diffWater = (int) (diff * rate / 1000);

        // 剩余的数量
        water = water - diffWater;
        if (water < 0) {
            water = 0;
        }

        // 剩余有水
        if (water > 0) {
            return true;
        } else {
            // 剩余没水了
            water = water + 1;
            currTime = System.currentTimeMillis();
            return false;
        }
    }
}
